<?php
/**
 * Created by PhpStorm.
 * User: hoter.zhang
 * Date: 2017/8/7
 * Time: 11:42
 */

namespace app\modules\admin\controllers;


use app\core\components\MysqlBackUp;
use Yii;
use yii\web\Response;

class DatabaseController extends AdminBaseController
{

    public function actionExport(){
        $this->setForward();
        $dbInfo = Yii::$app->db->createCommand('SHOW TABLE STATUS')->queryAll();
        $dbInfo = array_map('array_change_key_case', $dbInfo);
//        print_r($dbInfo);
        if (Yii::$app->request->isPost){
            Yii::$app->response->format = Response::FORMAT_JSON;
            $sql = new MysqlBackUp();
            $tables = $sql->getTables();

            if (!$sql->StartBackup()) {
                //render error
                $this->error('備份失敗','#',true);
//                die;
            }
            foreach ($tables as $tableName) {
                $sql->getColumns($tableName);
            }
            foreach ($tables as $tableName) {
                $sql->getData($tableName);
            }
            $sql->EndBackup();
            $this->success('操作成功', $this->getForward(), true);
        }
        return $this->render('export', [
            'dbInfo' => $dbInfo,
        ]);
    }

    public function actionImport() {
        return $this->render('import', [

        ]);
    }

    public function actionRepairOpt() {
        $operation = Yii::$app->request->get('operation', '');
        $tables = Yii::$app->request->get('tables', '');
        if($tables && in_array($operation, ['repair', 'optimize'])) {
            Yii::$app->db->createCommand($operation.' TABLE '.$tables);
            $this->success('操作成功', $this->getForward(), true);
            //return $this->redirect(['export']);
        } else {
            $this->error('操作失敗','#',true);
        }
    }
}